package com.bwei.topnews.manager;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.bwei.topnews.R;
import com.bwei.topnews.bean.CityInfo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by qwe on 2016/11/15.
 */
public class DBManager {


    private final Context context;
    private final File targeFile;

    public DBManager(Context context) {
        this.context = context;
        // 定义存储路径
        File file = Environment.getExternalStorageDirectory();

        File dirFile = new File(file, "toutiaodb");

        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        targeFile = new File(dirFile, "city.db");
    }

    public void copy() {
        InputStream inputStream=null;
        BufferedOutputStream out=null;
        try {
            inputStream= context.getResources().openRawResource(R.raw.china_city_name);
            out = new BufferedOutputStream(new FileOutputStream(targeFile));
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer))!=-1){
                out.write(buffer,0,len);
                out.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    List<CityInfo> list = new ArrayList<>();

    public List<CityInfo> getCityList(){

        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(targeFile, null);
        Cursor cursor = db.rawQuery("select * from T_city ", null);
        while(cursor.moveToNext()){
            String cityName = cursor.getString(cursor.getColumnIndex("CityName"));
            String nameSort = cursor.getString(cursor.getColumnIndex("NameSort"));
            list.add(new CityInfo(cityName,nameSort));
        }
        // 进行排序
        Collections.sort(list);

        for (int i = 0; i < list.size(); i++) {
            if(i == 0){
                list.get(i).setFlag(true);
            }else{
                if(list.get(i-1).getNamesort().equals(list.get(i).getNamesort())){
                    list.get(i).setFlag(false);
                }else{
                    list.get(i).setFlag(true);
                }
            }
        }
        return  list;
    }
}
